package com.hzdp.web.captcha;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;

import com.hzdp.web.action.BaseAction;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class JCaptchaAction extends BaseAction {

	/**
	 * @see org.apache.struts2.dispatcher.StreamResult#setInputName(String)
	 */
	private InputStream inputStream;

	public InputStream getInputStream() {
		return inputStream;
	}

	@Autowired
	private JCaptchaService jCaptchaService;

	@SuppressWarnings("restriction")
	public String execute() {
		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			String captchaId = getUUID();
			// call the ImageCaptchaService getChallenge method
			JCaptchaBufferedImage challenge = jCaptchaService.generate(captchaId);

			// a jpeg encoder
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);

			captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

			// flush it in the response
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);

			inputStream = new ByteArrayInputStream(captchaChallengeAsJpeg);
		} catch (Exception e) {
			e.printStackTrace();
			return FAIL;
		}

		return SUCCESS;
	}
}
